package tree.leetcode_129_medium;

public class SumNumbers {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        Integer i = sumNumbers(root);
        System.out.println(i);
    }

    public static int sumNumbers(TreeNode root) {
        return dfs(root, 0);
    }

    public static int dfs(TreeNode root, int sum) {
        if (root == null) {
            return 0;
        }
        //每一层的和 = 上一层根节点 * 10 + 本层节点值。
        /*
            1
           / \
          2   3

          1 = 0 * 10 + 1 = 1;
          2 = 1 * 10 + 2 = 12;
          3 = 1 * 10 + 3 = 13;

          左 == null  右 == null  叶子节点，返回
         */
        sum = sum * 10 + root.val;
        if (root.left == null && root.right == null) {
            return sum;
        }
        return dfs(root.left, sum) + dfs(root.right, sum);
    }
}
